package com.add.petback.controller;

import com.add.petback.model.Seller;
import com.add.petback.model.User;
import com.add.petback.service.SellerService;
import com.add.petback.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.JsonTransformation;

@Controller
@RequestMapping("/login")
//2016112460单富莛
public class LoginController {

    @Autowired(required = false)
    private UserServiceImpl userService;

    @Autowired(required = false)
    private SellerService sellerservice;

    @PostMapping("/user")
    @ResponseBody
    public String loginuser(@RequestBody String str) {
        // 获取从前端传回的User实例
        User user = JsonTransformation.jsonToObject(str, User.class);
        User foundUser = userService.find(user);

        // 如果查找到的User为空则返回404
        if (foundUser == null)
            return "404";
        return JsonTransformation.objectToJson(foundUser);
    }


    @PostMapping("/seller")
    @ResponseBody
    //2016112460单富莛
    public String loginseller(@RequestBody String str) {
        Seller seller = JsonTransformation.jsonToObject(str, Seller.class);
        Seller foundSeller = sellerservice.find(seller);

        if (foundSeller == null)
            return "404";
        return JsonTransformation.objectToJson(foundSeller);
    }

    @PostMapping("/regist")
    @ResponseBody
    //2016112460单富莛
    public String regist(@RequestBody String str) {
        User user = JsonTransformation.jsonToObject(str, User.class);
        try {
            userService.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
            return "404";
        }
        return "200";
    }


    @PostMapping("/forgetpassword")
    @ResponseBody
    //2016112460单富莛
    public String forgetpassword(@RequestBody String str) {
        User user = JsonTransformation.jsonToObject(str, User.class);
        User nullUser = new User();
        nullUser.setPhonenumber(user.getPhonenumber());
        try {
            User founduser = userService.find(nullUser);
            founduser.setPassword(user.getPassword());

            userService.save(founduser);
        } catch (Exception e) {
            e.printStackTrace();
            return "404";
        }
        return "200";
    }



}
